<?php

/**
 * Description of Files
 *
 * @author Fabrice
 */
class Application_Model_Files {
    
    protected $_baseDir = "";

    /**
     * Extrait le zip, deplace dans archive
     * @param type $file_to_open
     */
    public function openZip($file_to_open) {

        $target = $this->getBaseDir() .'/import/';
        $this->tryCreateDir($target);

        $zip = new ZipArchive();
        $x = $zip->open($file_to_open);
        if ($x === true) {
            $zip->extractTo($target);
            $zip->close();

            $archive = $this->getBaseDir() . '/archive/';
            $this->tryCreateDir($archive);
            #renomme le fichier zip et on l'archive.
            rename($file_to_open, $archive . basename($file_to_open));
        } else {
            die("There was a problem. Please try again!");
        }
    }

    /**
     * CrÃ©e un dossier de faÃ§on rÃ©cursive si celui n'existe pas
     *
     * @param string $dir
     */
    public function tryCreateDir($dirs) {
        if (!is_array($dirs)) {
            $dirs = array($dirs);
        }
        foreach ($dirs as $dir) {
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
        }
    }

    public function removeAllFiles($fileName = NULL) {
        $dir = $this->getBaseDir() .'/import/';
        $Allfiles = ($fileName) ? glob($dir . "$fileName.*") : glob($dir . "*.*") ;

        foreach ($Allfiles as $file) {
            unlink($file);
        }
    }

    /* ###################
     * GETTERS & SETTERS
     * ##################
     */

    public function getBaseDir() {
        if ("" == $this->_baseDir)
            $this->setBaseDir();
        return $this->_baseDir;
    }

    private function setBaseDir() {
        $this->_baseDir = $dir = APPLICATION_PATH  . '/models/DB/';
    }
}
?>
